<template>
  <div class="creator-center">
    <el-container style="height: 100vh;">
      <!-- 左侧菜单 -->
      <el-aside width="200px">
        <el-menu
          :default-active="currentMenu"
          class="el-menu-vertical-demo"
          @select="handleSelect"
        >
          <el-menu-item index="info">
            <i class="el-icon-user"></i>个人中心
          </el-menu-item>
          <el-menu-item index="articles">
            <i class="el-icon-document"></i>我的文章
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主区域 -->
      <el-main>
        <UserInfo v-if="currentMenu === 'info'" />

        <ArticleList
          v-if="currentMenu === 'articles' && !showNewArticle"
          :articles="articles"
          @create="openCreateArticle"
          @edit="openEditArticle"
          @delete="deleteArticle"
        />

        <!-- 传入articleId（编辑时）或 null（新建时） -->
        <NewArticle
          v-if="currentMenu === 'articles' && showNewArticle"
          :articleId="editingArticleId"
          @cancel="closeArticleEditor"
          @saved="handleArticleSaved"
        />
      </el-main>
    </el-container>

    <el-button
      class="back-home-btn"
      type="primary"
      size="large"
      @click="goHome"
    >
      返回首页
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import UserInfo from '@/components/creator/UserInfo.vue'
import ArticleList from '@/components/creator/ArticleList.vue'
import NewArticle from '@/components/creator/NewArticle.vue'

import * as articleApi from '@/api/article'
import { getAllTags } from '@/api/tag'
import { useUserStore } from '@/stores/user'

interface Article {
  id: number
  title: string
  content: string
  tags: string[]
  date: string
}

const router = useRouter()
const userStore = useUserStore()

const MENU_STORAGE_KEY = 'creator-center-current-menu'
const currentMenu = ref<'info' | 'articles'>(localStorage.getItem(MENU_STORAGE_KEY) as 'info' | 'articles' || 'info')

const articles = ref<Article[]>([])

const tagsList = ref<{ id: number; name: string }[]>([])

const showNewArticle = ref(false)
const editingArticleId = ref<number | null>(null)  // 存文章id，新建时为null

async function loadTags() {
  try {
    const res = await getAllTags()
    if (res.code === 0 && Array.isArray(res.data)) {
      tagsList.value = res.data
    } else {
      ElMessage.warning(res.message || '获取标签失败')
    }
  } catch (error) {
    ElMessage.error('请求标签失败')
    console.error(error)
  }
}

// 这里应该从接口拉文章列表，简化示例使用空数组
async function loadArticles() {
  // TODO: 根据你的后端接口，调用文章列表API
  // 示例：
  // const res = await articleApi.getMyArticles()
  // if (res.code === 0) articles.value = res.data
  // else ElMessage.error(res.message || '获取文章失败')
}

function handleSelect(index: string) {
  if (index === 'info' || index === 'articles') {
    currentMenu.value = index
    showNewArticle.value = false
    localStorage.setItem(MENU_STORAGE_KEY, index)
  }
}

onMounted(() => {
  const saved = localStorage.getItem(MENU_STORAGE_KEY)
  if (saved === 'info' || saved === 'articles') {
    currentMenu.value = saved
  }
  loadTags()
  loadArticles()
})

function goHome() {
  router.push('/')
}

function openCreateArticle() {
  editingArticleId.value = null
  showNewArticle.value = true
}

function openEditArticle(article: Article) {
  editingArticleId.value = article.id
  showNewArticle.value = true
}

function closeArticleEditor() {
  showNewArticle.value = false
}

function tagsIdToName(ids: number[]): string[] {
  return tagsList.value.filter(tag => ids.includes(tag.id)).map(tag => tag.name)
}

async function handleArticleSaved(data: {
  id?: number
  title: string
  content: string
  tag_ids: number[]
}) {
  try {
    if (data.id) {
      // 编辑文章
      const res = await articleApi.updateArticle(data.id, {
        title: data.title,
        content: data.content,
        tag_ids: data.tag_ids,
      })
      if (res.code === 0) {
        const idx = articles.value.findIndex(a => a.id === data.id)
        if (idx !== -1) {
          articles.value[idx] = {
            ...articles.value[idx],
            title: data.title,
            content: data.content,
            tags: tagsIdToName(data.tag_ids),
            date: articles.value[idx].date,
            id: data.id,
          }
        }
        ElMessage.success('更新成功')
      } else {
        ElMessage.error(res.message || '更新失败')
        return
      }
    } else {
      // 新建文章
      const res = await articleApi.createArticle({
        title: data.title,
        content: data.content,
        author_id: userStore.userInfo.id,
        tag_ids: data.tag_ids,
      })
      if (res.code === 0) {
        articles.value.push({
          id: res.data.id,
          title: data.title,
          content: data.content,
          tags: tagsIdToName(data.tag_ids),
          date: new Date().toISOString().slice(0, 10),
        })
        ElMessage.success('创建成功')
      } else {
        ElMessage.error(res.message || '创建失败')
        return
      }
    }
    showNewArticle.value = false
  } catch (error) {
    ElMessage.error('请求失败')
    console.error(error)
  }
}

function deleteArticle(article: Article) {
  articles.value = articles.value.filter(a => a.id !== article.id)
}
</script>

<style scoped>
.creator-center {
  font-family: sans-serif;
}

.back-home-btn {
  position: fixed;
  bottom: 40px;
  right: 40px;
  z-index: 1000;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}
</style>
